package cn.ztr.ymcc.consumer;

import cn.ztr.ymcc.domain.MessageEmail;
import cn.ztr.ymcc.dto.MessageDTO;
import cn.ztr.ymcc.service.IMessageEmailService;
import com.alibaba.fastjson.JSON;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "ztr_email",
        topic = "ztr_topic",
        selectorExpression = "email"
)
public class EmailConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageEmailService emailService;

    @Override
    public void onMessage(MessageExt messageExt) {
        String message = new String(messageExt.getBody(), CharsetUtil.UTF_8);
        MessageDTO messageDTO = JSON.parseObject(message, MessageDTO.class);
        MessageEmail messageEmail = new MessageEmail();
        for (MessageDTO.Eamil eamil : messageDTO.getEamils()) {
            BeanUtils.copyProperties(eamil,messageEmail);
            BeanUtils.copyProperties(messageDTO,messageEmail);
            messageEmail.setSendTime(new Date());
            emailService.save(messageEmail);
        }
    }
}
